// 下载功能相关

// 全局下载状态管理
const downloadStates = {
    douyin: false,
    kuaishou: false,
    kuaishouBatch: false,
    bilibili: false,
    vmq: false,
    vmqBatch: false,
    tiefenquan: false,
    tiefenquanVideo: false
};

// 当前下载任务ID（用于停止下载）
const currentDownloadTasks = {
    douyin: null,
    kuaishou: null,
    kuaishouBatch: null,
    bilibili: null,
    vmq: null,
    vmqBatch: null,
    tiefenquan: null,
    tiefenquanVideo: null
};

// 更新按钮状态
function updateButtonState(type, isDownloading) {
    downloadStates[type] = isDownloading;
    
    const buttonMappings = {
        douyin: 'downloadBtn',
        kuaishou: 'kuaishouDownloadBtn',
        kuaishouBatch: 'kuaishouBatchDownloadBtn',
        bilibili: 'bilibiliDownloadBtn',
        vmq: 'vmqDownloadBtn',
        vmqBatch: 'vmqBatchDownloadBtn',
        tiefenquan: 'tiefenquanDownloadBtn',
        tiefenquanVideo: 'tiefenquanVideoDownloadBtn'
    };
    
    const buttonId = buttonMappings[type];
    const button = document.getElementById(buttonId);
    
    if (button) {
        if (isDownloading) {
            button.innerHTML = '<span>⏹️</span> 停止下载';
            button.className = button.className.replace('btn-primary', 'btn-danger');
        } else {
            // 恢复原始文本
            const originalTexts = {
                douyin: '<span>🚀</span> 开始解析',
                kuaishou: '<span>⚡</span> 开始解析',
                kuaishouBatch: '<span>📦</span> 开始批量下载',
                bilibili: '<span>📺</span> 开始解析',
                vmq: '<span>🎯</span> 开始解析',
                vmqBatch: '<span>📦</span> 开始批量解析',
                tiefenquan: '<span>💠</span> 开始解析',
                tiefenquanVideo: '<span>🎬</span> 开始解析'
            };
            button.innerHTML = originalTexts[type];
            button.className = button.className.replace('btn-danger', 'btn-primary');
        }
    }
}

// 停止下载
async function stopDownload(type) {
    const taskId = currentDownloadTasks[type];
    if (!taskId) return;
    
    try {
        const response = await fetch('/api/stop-download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                task_id: taskId,
                client_id: clientId
            })
        });
        
        const result = await response.json();
        addLogEntry(result.message);
        
        // 重置状态
        currentDownloadTasks[type] = null;
        updateButtonState(type, false);
    } catch (error) {
        addLogEntry(`停止下载失败: ${error.message}`, 'error');
    }
}

// 重置所有下载状态
function resetAllDownloadStates() {
    for (const type in downloadStates) {
        if (downloadStates[type]) {
            currentDownloadTasks[type] = null;
            updateButtonState(type, false);
        }
    }
}

// 开始下载
async function startDownload() {
    // 检查是否正在下载
    if (downloadStates.douyin) {
        await stopDownload('douyin');
        return;
    }
    
    const url = document.getElementById('videoUrl').value.trim();
    const savePath = document.getElementById('savePath').value.trim();
    
    if (!url) {
        addLogEntry('请输入视频链接', 'error');
        return;
    }
    
    // 更新按钮状态
    updateButtonState('douyin', true);
    currentDownloadTasks.douyin = clientId + '_douyin_' + Date.now();
    
    addLogEntry('开始下载任务...');
    
    try {
        const endpoint = currentMode === 'video' ? '/api/download/douyin-video' : '/api/download/douyin-image';
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                save_path: savePath,
                client_id: clientId,
                task_id: currentDownloadTasks.douyin
            })
        });
        
        const result = await response.json();
        addLogEntry(result.message);
    } catch (error) {
        addLogEntry(`请求失败: ${error.message}`, 'error');
        // 下载失败时重置状态
        updateButtonState('douyin', false);
        currentDownloadTasks.douyin = null;
    }
}

// 快手下载
async function startKuaishouDownload() {
    const url = document.getElementById('kuaishouUrl').value.trim();
    const savePath = document.getElementById('kuaishouPath').value.trim();

    if (!url) {
        addKuaishouLog('请输入快手视频链接', 'error');
        return;
    }

    addKuaishouLog('开始快手下载任务...');

    try {
        const response = await fetch('/api/download/kuaishou', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                save_path: savePath,
                client_id: clientId
            })
        });

        const result = await response.json();
        addKuaishouLog(result.message);
    } catch (error) {
        addKuaishouLog(`快手下载失败: ${error.message}`, 'error');
    }
}

// 快手批量下载
async function startKuaishouBatchDownload() {
    // 检查是否正在下载
    if (downloadStates.kuaishouBatch) {
        await stopDownload('kuaishouBatch');
        return;
    }

    const userId = document.getElementById('kuaishouUserId').value.trim();
    const savePath = document.getElementById('kuaishouBatchPath').value.trim();

    if (!userId) {
        addKuaishouLog('请输入快手用户ID', 'error');
        return;
    }

    // 更新按钮状态
    updateButtonState('kuaishouBatch', true);
    currentDownloadTasks.kuaishouBatch = clientId + '_kuaishouBatch_' + Date.now();

    addKuaishouLog(`开始快手批量下载任务 - 用户ID: ${userId}`);

    try {
        const response = await fetch('/api/download/kuaishou-batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                user_id: userId,
                save_path: savePath,
                client_id: clientId,
                task_id: currentDownloadTasks.kuaishouBatch
            })
        });

        const result = await response.json();
        addKuaishouLog(result.message);
    } catch (error) {
        addKuaishouLog(`快手批量下载失败: ${error.message}`, 'error');
        // 下载失败时重置状态
        updateButtonState('kuaishouBatch', false);
        currentDownloadTasks.kuaishouBatch = null;
    }
}

// 付费区下载
async function startVmqDownload() {
    const url = document.getElementById('vmqUrl').value.trim();
    const savePath = document.getElementById('vmqPath').value.trim();
    
    if (!url) {
        addLogEntry('请输入微密圈链接', 'error');
        return;
    }
    
    addLogEntry('开始微密圈下载任务...');
    
    try {
        const response = await fetch('/api/download/vmq', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                save_path: savePath,
                client_id: clientId
            })
        });
        
        const result = await response.json();
        addLogEntry(result.message);
    } catch (error) {
        addLogEntry(`微密圈下载失败: ${error.message}`, 'error');
    }
}

// 微密圈批量下载
async function startVmqBatchDownload() {
    // 检查是否正在下载
    if (downloadStates.vmqBatch) {
        await stopDownload('vmqBatch');
        return;
    }
    
    const category = document.getElementById('vmqBatchCategory').value.trim();
    const page = document.getElementById('vmqBatchPage').value.trim();
    const savePath = document.getElementById('vmqBatchPath').value.trim();
    
    if (!category) {
        addLogEntry('请输入分类名称', 'error');
        return;
    }
    
    if (!page || isNaN(parseInt(page)) || parseInt(page) < 1) {
        addLogEntry('请输入有效的页码（大于0的数字）', 'error');
        return;
    }
    
    // 更新按钮状态
    updateButtonState('vmqBatch', true);
    currentDownloadTasks.vmqBatch = clientId + '_vmqBatch_' + Date.now();
    
    addLogEntry(`开始微密圈批量下载任务 - 分类: ${category}, 页码: ${page}`);
    
    try {
        const response = await fetch('/api/download/vmq-batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                category: category,
                page: parseInt(page),
                save_path: savePath,
                client_id: clientId,
                task_id: currentDownloadTasks.vmqBatch
            })
        });
        
        const result = await response.json();
        addLogEntry(result.message);
    } catch (error) {
        addLogEntry(`微密圈批量下载失败: ${error.message}`, 'error');
        // 下载失败时重置状态
        updateButtonState('vmqBatch', false);
        currentDownloadTasks.vmqBatch = null;
    }
}

// 铁粉圈下载
async function startTiefenquanDownload() {
    const url = document.getElementById('tiefenquanUrl').value.trim();
    const savePath = document.getElementById('tiefenquanPath').value.trim();
    
    if (!url) {
        addLogEntry('请输入铁粉圈链接', 'error');
        return;
    }
    
    addLogEntry('开始铁粉圈下载任务...');
    
    try {
        const response = await fetch('/api/download/vmq', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                save_path: savePath,
                client_id: clientId
            })
        });
        
        const result = await response.json();
        addLogEntry(result.message);
    } catch (error) {
        addLogEntry(`铁粉圈下载失败: ${error.message}`, 'error');
    }
}

// 清空微密圈批量下载日志
function clearVmqBatchLog() {
    const logArea = document.getElementById('vmqBatchLogArea');
    if (logArea) {
        logArea.innerHTML = `
            <div class="log-entry">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                <span>批量下载日志已清空，等待新任务...</span>
            </div>
        `;
    }
}

// 清空铁粉圈下载日志
function clearTiefenquanLog() {
    const logArea = document.getElementById('tiefenquanLogArea');
    if (logArea) {
        logArea.innerHTML = `
            <div class="log-entry">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                <span>铁粉圈日志已清空，等待新任务...</span>
            </div>
        `;
    }
}

// 铁粉圈视频下载
async function startTiefenquanVideoDownload() {
    // 检查是否正在下载
    if (downloadStates.tiefenquanVideo) {
        await stopDownload('tiefenquanVideo');
        return;
    }

    const url = document.getElementById('tiefenquanVideoUrl').value.trim();
    const savePath = document.getElementById('tiefenquanVideoPath').value.trim();

    if (!url) {
        addTiefenquanVideoLog('❌ 请输入铁粉圈视频链接！', 'error');
        return;
    }

    if (!savePath) {
        addTiefenquanVideoLog('❌ 请选择保存路径！', 'error');
        return;
    }

    // 验证URL格式
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        addTiefenquanVideoLog('❌ 请输入有效的网页链接！', 'error');
        return;
    }

    // 验证是否是铁粉圈链接
    if (!url.toLowerCase().includes('tiefenquan')) {
        addTiefenquanVideoLog('❌ 请输入有效的铁粉圈链接！', 'error');
        return;
    }

    // 更新下载状态
    updateButtonState('tiefenquanVideo', true);
    currentDownloadTasks.tiefenquanVideo = clientId + '_tiefenquanVideo_' + Date.now();

    // 重置进度条
    updateTiefenquanVideoProgress(0, '准备下载...');

    // 添加开始日志
    addTiefenquanVideoLog('🚀 开始铁粉圈视频下载...', 'info');
    addTiefenquanVideoLog(`📎 链接: ${url}`, 'info');
    addTiefenquanVideoLog(`📁 保存路径: ${savePath}`, 'info');

    try {
        const response = await fetch('/api/download/tiefenquan-video', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                save_path: savePath,
                client_id: getClientId()
            })
        });

        const result = await response.json();

        if (response.ok) {
            addTiefenquanVideoLog(`✅ ${result.message}`, 'success');
        } else {
            throw new Error(result.detail || '下载请求失败');
        }

    } catch (error) {
        console.error('铁粉圈视频下载错误:', error);
        addTiefenquanVideoLog(`❌ 下载失败: ${error.message}`, 'error');
        updateButtonState('tiefenquanVideo', false);
    }
}

// 更新铁粉圈视频下载进度
function updateTiefenquanVideoProgress(progress, text) {
    const progressFill = document.getElementById('tiefenquanVideoProgressFill');
    const progressText = document.getElementById('tiefenquanVideoProgressText');

    if (progressFill) {
        progressFill.style.width = `${progress}%`;
    }

    if (progressText) {
        progressText.textContent = text || `${progress}%`;
    }
}

// 添加铁粉圈视频下载日志
function addTiefenquanVideoLog(message, type = 'info') {
    const logArea = document.getElementById('tiefenquanVideoLogArea');
    if (!logArea) return;

    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;

    const time = new Date().toLocaleTimeString();
    logEntry.innerHTML = `
        <span class="log-time">[${time}]</span>
        <span>${message}</span>
    `;

    logArea.appendChild(logEntry);
    logArea.scrollTop = logArea.scrollHeight;
}

// 重置铁粉圈视频下载按钮
function resetTiefenquanVideoDownloadButton() {
    updateButtonState('tiefenquanVideo', false);
    updateTiefenquanVideoProgress(0, '准备就绪');
}

// 清空铁粉圈视频下载日志
function clearTiefenquanVideoLog() {
    const logArea = document.getElementById('tiefenquanVideoLogArea');
    if (logArea) {
        logArea.innerHTML = `
            <div class="log-entry">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                <span>铁粉圈视频日志已清空，等待新任务...</span>
            </div>
        `;
    }
}

// ============================================
//   📺 B站下载相关功能
// ============================================

// B站视频下载
async function startBilibiliDownload() {
    // 检查是否正在下载
    if (downloadStates.bilibili) {
        await stopDownload('bilibili');
        return;
    }

    const url = document.getElementById('bilibiliUrl').value.trim();
    const savePath = document.getElementById('bilibiliPath').value.trim();

    if (!url) {
        addBilibiliLog('请输入B站视频链接', 'error');
        return;
    }

    // 更新按钮状态
    updateButtonState('bilibili', true);
    currentDownloadTasks.bilibili = clientId + '_bilibili_' + Date.now();

    addBilibiliLog(`开始B站视频下载任务 - 链接: ${url}`);

    try {
        const response = await fetch('/api/download/bilibili', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                save_path: savePath,
                client_id: clientId,
                task_id: currentDownloadTasks.bilibili
            })
        });

        const result = await response.json();
        addBilibiliLog(result.message);
    } catch (error) {
        addBilibiliLog(`B站视频下载失败: ${error.message}`, 'error');
        // 下载失败时重置状态
        updateButtonState('bilibili', false);
        currentDownloadTasks.bilibili = null;
    }
}

// 浏览B站保存路径
function browseBilibiliPath() {
    // 这里可以添加文件选择器逻辑
    // 目前先显示提示
    addBilibiliLog('请手动输入保存路径，或使用默认路径', 'info');
}

// 更新B站下载进度
function updateBilibiliProgress(progress, text) {
    const progressFill = document.getElementById('bilibiliProgressFill');
    const progressText = document.getElementById('bilibiliProgressText');

    if (progressFill) {
        progressFill.style.width = `${progress}%`;
    }

    if (progressText) {
        progressText.textContent = text || `${progress}%`;
    }
}

// 添加B站下载日志
function addBilibiliLog(message, type = 'info') {
    const logArea = document.getElementById('bilibiliLogArea');
    if (!logArea) {
        console.error('bilibiliLogArea element not found!');
        return;
    }

    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;

    const time = new Date().toLocaleTimeString();
    logEntry.innerHTML = `
        <span class="log-time">[${time}]</span>
        <span>${message}</span>
    `;

    logArea.appendChild(logEntry);
    logArea.scrollTop = logArea.scrollHeight;
}

// 重置B站下载按钮
function resetBilibiliDownloadButton() {
    updateButtonState('bilibili', false);
    updateBilibiliProgress(0, '准备就绪');
}

// 清空B站下载日志
function clearBilibiliLog() {
    const logArea = document.getElementById('bilibiliLogArea');
    if (logArea) {
        logArea.innerHTML = `
            <div class="log-entry">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                <span>📺 B站解析系统已启动，等待任务...</span>
            </div>
        `;
    }
}

// ============================================
//   ⚡ 快手下载相关功能
// ============================================

// 浏览快手保存路径
function browseKuaishouPath() {
    // 这里可以添加文件选择器逻辑
    // 目前先显示提示
    addKuaishouLog('请手动输入保存路径，或使用默认路径', 'info');
}

// 浏览快手批量下载保存路径
function browseKuaishouBatchPath() {
    // 这里可以添加文件选择器逻辑
    // 目前先显示提示
    addKuaishouLog('请手动输入保存路径，或使用默认路径', 'info');
}

// 更新快手下载进度
function updateKuaishouProgress(progress, text) {
    const progressFill = document.getElementById('kuaishouProgressFill');
    const progressText = document.getElementById('kuaishouProgressText');

    if (progressFill) {
        progressFill.style.width = `${progress}%`;
    }

    if (progressText) {
        progressText.textContent = text || `${progress}%`;
    }
}

// 添加快手下载日志
function addKuaishouLog(message, type = 'info') {
    const logArea = document.getElementById('kuaishouLogArea');
    if (!logArea) {
        console.error('kuaishouLogArea element not found!');
        return;
    }

    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;

    const time = new Date().toLocaleTimeString();
    logEntry.innerHTML = `
        <span class="log-time">[${time}]</span>
        <span>${message}</span>
    `;

    logArea.appendChild(logEntry);
    logArea.scrollTop = logArea.scrollHeight;
}

// 重置快手下载按钮
function resetKuaishouDownloadButton() {
    updateButtonState('kuaishou', false);
    updateKuaishouProgress(0, '准备就绪');
}

// 清空快手下载日志
function clearKuaishouLog() {
    const logArea = document.getElementById('kuaishouLogArea');
    if (logArea) {
        logArea.innerHTML = `
            <div class="log-entry">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                <span>⚡ 快手解析系统已启动，等待任务...</span>
            </div>
        `;
    }
}

// 清空快手批量下载日志
function clearKuaishouBatchLog() {
    const logArea = document.getElementById('kuaishouLogArea');
    if (logArea) {
        logArea.innerHTML = `
            <div class="log-entry">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                <span>⚡ 快手批量下载系统已启动，等待任务...</span>
            </div>
        `;
    }
}
